package com.ybear.ybcomponent.base.adapter.pager;

import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.ybear.ybcomponent.base.adapter.OnViewPagerAdapterListener;

import java.util.List;

/**
 * Pager适配器
 *
 * 需要用到适配器的组件及方法
 * @see ViewPager
 * @see ViewPager#setAdapter(PagerAdapter)
 *
 * 传入一个集合View，设置适配器后以实现多个View之间的滑动切换
 * @param <V>
 */
public class ViewPagerAdapter<V extends View> extends PagerAdapter {
    private final List<V> mViewList;

    private OnViewPagerAdapterListener mOnViewPagerAdapterListener;

    public ViewPagerAdapter(List<V> list) { mViewList = list; }

    public void setOnViewPagerAdapterListener(OnViewPagerAdapterListener l) {
        mOnViewPagerAdapterListener = l;
    }

    /**
     * 添加页面
     * @param container     {@link ViewGroup}
     * @param position      下标
     * @return              当前下标的View
     */
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        Object ret;
        if( mOnViewPagerAdapterListener != null ) {
            ret = mOnViewPagerAdapterListener.instantiateItem( container, position );
            if( ret != null ) return ret;
        }
        ret = getItem( position );
        try {
            View v = (View) ret;
            if( v == null ) return null;
            if( v.getLayoutParams() == null ) {
                container.addView( v );
            }else {
                container.addView( v, v.getLayoutParams() );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 删除页面
     * @param container     {@link ViewGroup}
     * @param position      下标
     * @param object        {@link //Object}
     */
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        boolean ret = false;
        if( mOnViewPagerAdapterListener != null ) {
            ret = mOnViewPagerAdapterListener.destroyItem( container, position, object );
        }
        if( !ret ) container.removeView( (View) object );
    }

    /**
     * 页面数量
     * @return          页面数量
     */
    @Override
    public int getCount() {
        return mViewList.size();
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        return POSITION_NONE;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    @Nullable
    public View getItem(int position) {
        if( position < 0 || position >= mViewList.size() ) return null;
        return mViewList.get( position );
    }
}
